package org.springframework.beans.factory.support;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Name CglibSubclassInstantiationStrategy
 * @Description: Bean 实例化策略 [实现] 类
 * 描述信息：使用 CGLIB 动态生成子类。
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-03-15 13:52:28
 **/
public class CglibSubclassInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition beanDefinition) throws BeansException {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        enhancer.setCallback(new MethodInterceptor() {
            /**
             * 目标方法拦截器
             * @param proxy 代理对象
             * @param method 目标方法
             * @param args 目标方法入参
             * @param methodProxy 代理方法
             * @return java.lang.Object 目标方法返回值
             * @version v1.0.0
             * @author lichao
             * @date 2024-03-15 13:58:01
             */
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                return methodProxy.invokeSuper(proxy, args);
            }
        });
        return enhancer.create();
    }
}

